package com.mbc.rmt.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.mbc.rmt.entities.PaymentTypeDetail;
import com.mbc.common.dao.DAO;

public class PaymentTypeDetailDAOImpls extends DAO<PaymentTypeDetail> implements PaymentTypeDetailDAO {

	public PaymentTypeDetailDAOImpls(Connection conn)
	{
		this.conn = conn;
		this.table_name = "PaymentTypeDetail";
	}

	@Override
	public void create(PaymentTypeDetail entity) throws SQLException {
		query = "insert into " + table_name + " ( PaymentTypeDetailId, PaymentTypeId, AddCodeId, Sender) values( ?, ?, ?, ?)";
		pstmt = conn.prepareStatement(query);
		int i = 1;
				pstmt.setLong(i++, entity.getPaymentTypeDetailId());
		pstmt.setLong(i++, entity.getPaymentTypeId());
		pstmt.setLong(i++, entity.getAddCodeId());
		pstmt.setString(i++, entity.getSender());

		pstmt.executeUpdate();
		pstmt.close();
	}
	
	@Override
	protected PaymentTypeDetail readRecord(ResultSet rs) throws SQLException {
		PaymentTypeDetail l_entity = new PaymentTypeDetail();
		l_entity.setPaymentTypeDetailId(rs.getLong("PaymentTypeDetailId"));
		l_entity.setPaymentTypeId(rs.getLong("PaymentTypeId"));
		l_entity.setAddCodeId(rs.getLong("AddCodeId"));
		l_entity.setSender(rs.getString("Sender"));

		return l_entity;
	}

	@Override
	public void deleteByPaymentTypeId(long paymentTypeId) throws SQLException {
		query = getDeleteQuery() + " where PaymentTypeId = " + paymentTypeId;
		pstmt = conn.prepareStatement(query);
		pstmt.executeUpdate();
		pstmt.close();
	}

	@Override
	public List<PaymentTypeDetail> findByPaymentTypeId(long paymentTypeId)
			throws SQLException {
		ArrayList<PaymentTypeDetail> l_list = new ArrayList<PaymentTypeDetail>();
		query = "select a.*, b.Code from paymenttypedetail as a inner join addcode as b on a.addcodeid = b.addcodeid where a.paymenttypeid = " + paymentTypeId;
		pstmt = conn.prepareStatement(query);
		rs = pstmt.executeQuery();
		while (rs.next()) {
			PaymentTypeDetail l_detail = readRecord(rs);
			l_detail.setAddCode(rs.getString("Code"));
			l_list.add(l_detail);
		}
		rs.close();
		pstmt.close();
		return l_list;
	}
}
